import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'

import getRoutes from './register'
import type { App } from 'vue'

//获取动态路由
const routes: RouteRecordRaw[] = getRoutes()

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/admin',
    },
    {
      name: 'not-found',
      path: '/:pathMatch(.*)*',
      redirect: '/auth/404',
    },
    ...routes,
  ],
})

const setup = async (app: App) => {
  app.use(router)

  //守卫
  router.beforeEach(async (to, from, next) => {
    // 开始 loadingBar
    window.$loadingBar?.start()

    if (to.name === 'auth.login') {
      next()
      return
    }

    //验证登录
    if (!useAuth().isLogin()) {
      const redirect = to.fullPath
      next({ name: 'auth.login', query: { redirect } })
    }

    // 外链路由, 从新标签打开，返回上一个路由
    if (to.meta.href) {
      window.open(to.meta.href as string)
      next({ path: from.fullPath, replace: true, query: from.query })
    }
    next()
  })
  router.afterEach(() => {
    // 结束 loadingBar
    window.$loadingBar?.finish()
  })

  await router.isReady()
}
export { setup }
export default router
